import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet, ScrollView, TouchableOpacity, RefreshControl, Alert } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { SafeAreaView } from 'react-native-safe-area-context';

const MyMain = ({ navigation }) => {
  const [isLogin, setIsLogin] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [userProfile, setUserProfile] = useState({
    avatar: require('../assets/default_avatar.png'),
    nickname: '点击登录',
    userId: ''
  });
  const [userPreferences, setUserPreferences] = useState([]);
  const [userCustomTags, setUserCustomTags] = useState([]);

  // 添加 features 数组
  const features = [
    { id: 'history', icon: <Icon name="history" size={24} color="#363636" />, name: '历史记录' },
    { id: 'preferences', icon: <Icon name="heart" size={24} color="#363636" />, name: '个人偏好' },
    { id: 'editProfile', icon: <Icon name="user" size={24} color="#363636" />, name: '修改资料' },
    { id: 'settings', icon: <Icon name="cog" size={24} color="#363636" />, name: '   设置    ' },
  ];

  // 获取用户信息的函数
  const fetchUserProfile = async () => {
    try {
      const token = await AsyncStorage.getItem('authToken');
      console.log('当前My页面token:', token);
      if (!token) {
        setIsLogin(false);
        // navigation.navigate('LoginPage');
        return;
      }
      // 获取用户信息
      const response = await fetch('http://124.222.104.145:8003/user/profile/', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      console.log('profile接口状态码:', response.status);
      const text = await response.text();
      console.log('profile接口返回内容:', text);

      // 处理未授权
      if (response.status === 401 || response.status === 403) {
        await AsyncStorage.removeItem('authToken');
        setIsLogin(false);
        Alert.alert('登录已过期', '请重新登录');
        // navigation.navigate('LoginPage');
        return;
      }

      const contentType = response.headers.get('content-type');
      if (contentType && contentType.indexOf('application/json') !== -1) {
        const data = JSON.parse(text);
        console.log(data); // 调试输出获取的数据

        setUserProfile({
          avatar: data.profile_picture ? { uri: `http://124.222.104.145:8003${data.profile_picture}` } : require('../assets/default_avatar.png'),
          nickname: data.nickname || data.username || '书海漫游者',
          userId: `用户ID: ${data.id || '未知'}`
        });

        // 获取个人偏好
        const prefRes = await fetch('http://124.222.104.145:8003/user/preference/', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        const prefContentType = prefRes.headers.get('content-type');
        const prefText = await prefRes.text();
        if (prefContentType && prefContentType.indexOf('application/json') !== -1) {
          const prefData = JSON.parse(prefText);
          setUserPreferences(prefData.default_tags || []);
          setUserCustomTags((prefData.tags || []).map(t => t.name));
        } else {
          setUserPreferences([]);
          setUserCustomTags([]);
        }
        setIsLogin(true);
      } else {
        console.error('profile接口返回非JSON:', text);
        setIsLogin(false);
        // navigation.navigate('LoginPage');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      setIsLogin(false);
    }
  };

  // 处理下拉刷新
  const onRefresh = async () => {
    setRefreshing(true);
    await fetchUserProfile();
    setRefreshing(false);
  };

  // 处理头像区域点击
  const handleProfilePress = () => {
    if (!isLogin) {
      navigation.navigate('LoginPage');
    } else {
      navigation.navigate('ProfileEdit'); // 登录状态下跳转到修改资料页面
    }
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={handleProfilePress}>
        <View style={styles.header}>
          <Image source={userProfile.avatar} style={styles.avatar} />
          <View style={styles.userInfo}>
            <Text style={styles.username}>{userProfile.nickname}</Text>
            {isLogin && <Text style={styles.userId}>{userProfile.userId}</Text>}
          </View>
        </View>
      </TouchableOpacity>

      {/* 标签区，带横线 */}
      {isLogin && (userPreferences.length > 0 || userCustomTags.length > 0) && (
        <>
          <View style={styles.divider} />
          <View style={styles.preferenceTagContainer}>
            {[...userPreferences, ...userCustomTags].map(tag => (
              <View key={tag} style={styles.preferenceTag}>
                <Text style={styles.preferenceTagText}>{tag}</Text>
              </View>
            ))}
          </View>
          <View style={styles.divider} />
        </>
      )}

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#4CAF50']}
            tintColor="#4CAF50"
          />
        }
      >
        {features.map((feature) => (
          <TouchableOpacity
            key={feature.id}
            style={styles.item}
            onPress={() => {
              if (!isLogin) {
                navigation.navigate('LoginPage');
                return;
              }
              switch (feature.id) {
                case 'history':
                  navigation.navigate('History');
                  break;
                case 'editProfile':
                  navigation.navigate('ProfileEdit');
                  break;
                case 'settings':
                  navigation.navigate('MySetting');
                  break;
                case 'preferences':
                  navigation.navigate('PreferenceEdit');
                  break;
              }
            }}
          >
          
            <View style={[styles.itemParent,styles.itemParentPosition]}>
              
            <View style={styles.itemLeft}>
              <Text style={styles.itemText}>{feature.name}</Text>
              {React.cloneElement(feature.icon, { style: [feature.icon.props.style, styles.iconStyle] })}
              <Text style={styles.arrow}>›</Text>
            </View>
            
          </View>
          
          </TouchableOpacity>
          
        ))}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,  // 改为 flex: 1
    backgroundColor: '#f6f6f6',  // 改为白色背景
    width: '100%',  // 宽度自适应
    height: 741,
    overflow: 'hidden',
    paddingTop: 20,
    textAlign : 'center',
    justifyContent: 'center',
  },
  frameParent: {
    shadowColor: "rgba(0, 0, 0, 0.25)",
    shadowOffset: {
    width: 0,
    height: 4
    },
    shadowRadius: 4,
    elevation: 4,
    shadowOpacity: 1,
    backgroundColor: "#fff",
    flex: 1,
    width: "100%",
    height: 588,
    overflow: "hidden"
},
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    backgroundColor: '#fff',
    height: 100,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  userInfo: {
    flexDirection: 'column',
    alignItems: 'flex-start',
    marginLeft: 15,
  },
  avatar: {
    width: 60,  // 调整头像大小
    height: 60,
    borderRadius: 25,
    borderWidth: 1,
    borderColor: '#eee',
  },
  username: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#222',
    marginBottom: 2,
  },
  userId: {
    fontSize: 16,
    color: '#666',
    marginBottom: 6,
  },
  content: {
    flex: 1,  // 改为 flex: 1
    backgroundColor: '#fff',
    paddingTop: 10,
    paddingHorizontal: 15,
  },
  item: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 70,
    paddingHorizontal: 15,
    backgroundColor: '#fff',  // 改为白色背景
    marginBottom: 1,  // 添加细微间距
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  itemLeft: {
    top: 12,
    left: 6,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    position: 'absolute'
  },
  itemText: {
    fontSize: 18,
    fontWeight: '500',
    fontFamily:'MiSans VF',
    color: '#000',
  },
  arrow: {
    color: '#999',
    fontSize: 25,
    width:24,
    height:24,
    flex:1,
    left: 200,
  },
  divider: {
    height: 1,
    backgroundColor: '#eee',
    marginHorizontal: 0,
  },
  preferenceTagContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingVertical: 10,
    paddingHorizontal: 20,
    backgroundColor: '#fff',
  },
  preferenceTag: {
    backgroundColor: '#e8f5e9',
    borderRadius: 12,
    paddingHorizontal: 10,
    paddingVertical: 3,
    marginRight: 6,
    marginBottom: 4,
  },
  preferenceTagText: {
    color: '#388e3c',
    fontSize: 13,
  },
  iconStyle: {
    flex:1,
    height:24,
    width:24,
  },
  itemParent: {
    gap: 6,
  },
  itemParentPosition: {
    alignItems: "center",
    flexDirection: "row",
    left: 26,
    top: 12,
    position: "absolute"
  },
  frameGroup: {
    top:21,
  },
  frameLayout: {
    height: 46,
    width: 321,
    backgroundColor: "#f2f2f2",
    borderRadius: 6,
    left: "50%",
    marginLeft: -161,
    position: "absolute",
    overflow: "hidden"
  }
});

export default MyMain;